package com.example.tkserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.tkserver.entity.MyException;
import com.example.tkserver.utils.response.ResultData;
import com.example.tkserver.utils.response.ReturnCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 全局拦截器
 * @Auther: LiZhuoYi
 * @Date: 10/11/2022
 */
@RestControllerAdvice
@Log4j2
public class RestResponseController implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //如果是字符串 则转为json字符串
        if(o instanceof String){
            return objectMapper.writeValueAsString(ResultData.success(o));
        }
        //如果是正确的类型 则直接发给前端
        if(o instanceof ResultData){
            return o;
        }
        return ResultData.success(o);
    }

    /**
     * 默认全局异常处理。
     * @param e the e
     * @return JSONObject
     */
    @ExceptionHandler(Exception.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData exception(Exception e) {
//        log.error("全局异常信息 ex={}", e.getMessage(), e);
        //如果是自定义的异常 则输出异常消息
        if (e instanceof MyException){
            return ResultData.fail(ReturnCode.RC500.getCode(),e.getMessage());
        }
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return ResultData.fail(ReturnCode.RC500.getCode(),ReturnCode.RC500.getMessage());
    }
}
